package com.audaque.springboot.foshanupload.web.interceptor;

import com.audaque.springboot.foshanupload.web.anno.RAnno;
import com.audaque.springboot.foshanupload.core.constants.ComConst;
import com.audaque.springboot.foshanupload.web.constants.WebConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zgb
 * @desc 标记controller的@RAnno在类上还是方法上
 * @date 2022-01-25 21:54:43
 */
@Slf4j
public class RInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(RAnno.class)) {
                request.setAttribute(WebConst.R_ANNO, clazz.getAnnotation(RAnno.class));
            } else if (method.isAnnotationPresent(RAnno.class)) {
                request.setAttribute(WebConst.R_ANNO, method.getAnnotation(RAnno.class));
            }
        }
        return true;
    }


}
